<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/tool/account' }">公众号列表</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path:'/publicAccountManager/index?name='+name+'&username='+username}">公众号
            {{ name }} 管理
          </el-breadcrumb-item>
          <el-breadcrumb-item>编辑多图文消息</el-breadcrumb-item>

        </el-breadcrumb>
      </template>
    </el-card>

    <el-container>
      <el-aside style="width: 400px;background-color: white" >
          <el-card
                  @mouseenter="flag=true" @mouseleave="flag=false"
                  class="main-material"
                  :class="{'bgc':flag}"
                  body-style="margin-top:15px;padding: 0px; position: relative; min-height: 350px;">
              <img
                      v-show="dialogImageUrl!==''"
                      :src="dialogImageUrl"
                      height="250"
                      style="width: 100%"
              />
              <el-image v-show="dialogImageUrl===''"
                        style="width: 100%;height: 250px">
                  <template #error>
                      <div class="image-slot">
                          <el-icon>
                              <icon-picture/>
                          </el-icon>
                      </div>
                  </template>
              </el-image>
              <div class="main-material-title">
                  {{mainTitle}}
              </div>
              <div class="main-material-desc">{{mainSummary}}</div>
              <div class="material-edit-pan" v-show="flag">
                  <div title="编辑" class="edit-pan-left" @click="editMain">
                  </div>
              </div>

          </el-card>

          <el-card v-for="(item,index) in addArray" :key="item.id" @mouseenter="item.showFlag=true"
                   @mouseleave="item.showFlag=false" class=" secondary-material is-hover-shadow"
                   body-style="padding: 0px !important; position: relative;">
              <img
                      style="height: 80px; width: 80px;"
                      :src="item.imgUrl?item.imgUrl: ('')">
              <div class="secondary-material-title">{{item.mainTitle}}</div>
              <div class="material-edit-pan2" v-show="item.showFlag">
                  <div class="edit-pan-content">
                      <div title="编辑" @click="itemEdit(item,index)" class="edit-pan-left"></div>
                      <div title="删除" @click="itemDel(item)" class="edit-pan-right"></div>
                  </div>
              </div>
          </el-card>

          <el-card style="margin-top: 10px;" @click="addItem">
              <div class="add-sub-img-text">+</div>
          </el-card>
      </el-aside>
      <el-main>
         <div class="edit-tips">{{headTitle}}</div>
         <div class="edit-content-title">标题</div>
          <div>
            <el-input @input="titleChange"  v-model="title"   maxlength="36" show-word-limit
                          size="large" placeholder="请输入内容,最多36个字符" clearable></el-input>
          </div>
          <div  class="edit-content-summary">摘要</div>
          <div>
            <el-input  v-model="contentsummary"  @input="summaryInput"  maxlength="100" show-word-limit
                       size="large" placeholder="请输入内容,最多100个字符" clearable></el-input>
          </div>
          <div  class="edit-content-majorpic">封面（首图封面建议尺寸：720*400）</div>
          <el-checkbox v-model="checked1" label="在正文顶部显示封面图片" size="large" />
          <ImageUpload :limit="1" @update:modelValue="receiveUrl" :fileUrl="tempImageUrl"/>

          <div class="view-content-type m-t-20" v-show="showContent">
              <div class="view-content-type-title">请选择用户点击图文消息后查看的内容</div>
              <div class="flex-row">
                  <div class="flex-column cursor-point eidt-text" @click="toggleMainContext">
                      <img
                                                                       src=""
                                                                       width="120" height="120">
                      <span class="m-t-10" >编辑正文</span>
                  </div>
                  <div class="flex-column cursor-point goto-net" @click="toggleShowOther"><img
                                                                      src=""
                                                                      width="120" height="120"> <span
                          class="m-t-10">跳转至网页</span></div>
              </div>
          </div>
          <div class="content-type" v-show="showContextType">
              <div   class="content-type-edit-check">
                   <el-button @click="toggleShowMain">请选择</el-button>
                   <el-button @click="toggleShowOther">跳转至网页</el-button>
              </div>
              <div   class="quill-editor">
                  <div style="border: 1px solid #ccc">
                      <Toolbar
                              style="border-bottom: 1px solid #ccc"
                              :editor="editorRef"
                              :defaultConfig="toolbarConfig"
                              :mode="mode"
                      />
                      <Editor
                              style="height: 500px; overflow-y: hidden;"
                              v-model="tempHtmlValue"
                              :defaultConfig="editorConfig"
                              :mode="mode"
                              @onCreated="handleCreated"
                              @onChange="editChange"
                      />
                  </div>
              </div>
              <div   class="edit-content-original-link">添加原文链接</div>
              <el-input  @input="originalLinkInput" v-model="originalLink"   maxlength="100" show-word-limit
                         size="large" placeholder="请输入内容,最多100个字符" clearable></el-input>
          </div>
          <div v-show="showNetConfig">
              <div style="display: flex; justify-content: space-between;margin-top: 20px;
             align-items: center;
              ">
                  <div class="content-type-edit-check">添加跳转至网页链接</div>
                  <el-button @click="toggleMainContext">编辑正文</el-button>
              </div>

              <el-input style="margin-top: 20px;" v-model="netconfig"   maxlength="100" show-word-limit
                         size="large" placeholder="请输入内容,最多100个字符" clearable>

              </el-input>
          </div>
          <el-button style="margin-top: 10px;width: 100px;" type="primary" size="large"
           @click="save"
          >保存</el-button>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup name="duotuwen">
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import {ArrowRight, Picture as IconPicture} from '@element-plus/icons-vue'
    import {onBeforeUnmount, onMounted, reactive, ref, shallowRef} from 'vue'
    import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
    import {ElMessage, ElMessageBox} from 'element-plus'

    import usePublicAccount from '/@/stores/modules/publicaccount'
    import {IEditorConfig} from "@wangeditor/editor";
    import { Session } from '/@/utils/storage';
    import {commonUpload} from  '/@/utils/commonUpload.js'
    import {parseTime} from '/@/utils/timeutils'
    import {batchAddImagetext,listImagetext} from  '/@/api/publicaccount/imagetext'
    import {useRoute, useRouter} from "vue-router";

    const test=  ArrowRight;
    const test2= IconPicture;
    const test3 = Editor;
    const test4 = Toolbar;
    const publicAccount = usePublicAccount();
    const name = publicAccount.selectAccount;
    const username = publicAccount.selectid;
    const flag = ref(false)
    const title = ref("");
    const mainTitle = ref("");
    const contentsummary = ref("");
    const mainSummary =  ref("");
    const checked1 = ref(true);

    const fileList = ref<UploadUserFile[]>([])

    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const originalLink = ref("");
    const showContextType = ref(false);

    const handleRemove: (uploadFile, uploadFiles) => void = (uploadFile, uploadFiles) => {
        console.log(uploadFile, uploadFiles)
        dialogImageUrl.value = '';
    }

    const handleSuccess: (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => void = (response, uploadFile, uploadFiles) => {
        console.info("uploadFile", uploadFile, "uploadFiles:", uploadFiles);
        dialogImageUrl.value = uploadFile.url;
    }

    const handlePictureCardPreview: (uploadFile) => void = (uploadFile) => {
        dialogImageUrl.value = uploadFile.url!
        dialogVisible.value = true
    }

    const receiveUrl = (url) => {
         tempImageUrl.value =url;
         if(selectIndex.value ===-1){
            dialogImageUrl.value = url;
         }else{
            addArray[selectIndex.value].imgUrl = url;
         }
    }

    const tempImageUrl = ref(null);

    const showContent = ref(true);
    const editorRef = shallowRef()
    const valueHtml = ref('')
    const toolbarConfig = {}


    const baseUrl = import.meta.env.VITE_API_BASE_URL;
    const uploadApi = ref(import.meta.env.VITE_API_BASE_URL + "/common/upload");
    const headers = ref({Authorization: "Bearer " + Session.getToken()});

    const editorConfig: Partial<IEditorConfig> = {  // TS 语法
      MENU_CONF: {},
      placeholder: '请输入',
      // 其他属性...
    }
    editorConfig.MENU_CONF['codeSelectLang'] = {
      // 代码语言
      codeLangs: [
        { text: 'CSS', value: 'css' },
        { text: 'HTML', value: 'html' },
        { text: 'XML', value: 'xml' },
        // 其他
      ]
    }

    editorConfig.MENU_CONF['uploadImage'] = {
      server: uploadApi.value,
      fieldName: 'file',
      async customUpload(file: File, insertFn: InsertFnType) {  // TS 语法
        // async customUpload(file, insertFn) {                   // JS 语法
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        let result=  await commonUpload(file);
        console.info("result",result);
        insertFn(result.data.url,result.data.originalFilename,result.data.url);
      }
    }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })
    const mode= ref('default');

    const handleCreated = (editor) => {
        editorRef.value = editor // 记录 editor 实例，重要！
    }

    const toggleShowMain = () =>{
        showContent.value=true;
        showContextType.value=false;
    }

    const toggleMainContext = () => {
        showContent.value = false;
        showContextType.value = true;
        showNetConfig.value = false;
    }

    const showNetConfig = ref(false);
    const netconfig = ref("");

    const toggleShowOther = () => {
        showContent.value = false;
        showContextType.value = false;
        showNetConfig.value = true;
    }

    let addArray = reactive([{
        id: Date.now().valueOf(),
        showFlag: false,
        mainTitle: '',
        subTitle: '',
        imgUrl:'',
        body:'',
        originalLink:'',
       }
    ]);

    const addItem = () => {
        if (addArray.length < 4) {
            addArray.push({
                id: Date.now().valueOf(),
                showFlag: false,
            })
        } else {
            ElMessage({
                message: '仅支持添加4个',
                type: 'warning',
            })
        }
    }

    const materialEditPan2 = ref(false);
    const headTitle = ref("正在编辑主图文");
    const selectIndex = ref(-1);
    const tempHtmlValue = ref('');

    const itemEdit = (item,index) => {
         headTitle.value = "正在编辑第"+(index+1)+"个副图文";
         selectIndex.value= index;
         title.value = item.mainTitle;
         contentsummary.value = item.subTitle;
         tempImageUrl.value = item.imgUrl;
         tempHtmlValue.value = addArray[index].body
    }

    const editMain = () => {
      headTitle.value = "正在编辑主图文";
      selectIndex.value = -1;
      title.value = mainTitle.value;
      tempHtmlValue.value = valueHtml.value;
    }

    const summaryInput = (value) =>{
        if(selectIndex.value === -1){
            mainSummary.value =value;
            return;
        }
        addArray[selectIndex.value].subTitle= value;
    }
    const titleChange = (value) => {
         if(selectIndex.value === -1){
             mainTitle.value =value;
             return;
         }
         addArray[selectIndex.value].mainTitle= value;
    }

    const originalLinkInput = (value) =>{
      if(selectIndex.value === -1){
        originalLink.value =value;
        return;
      }
      addArray[selectIndex.value].originalLink= value;
    }



    editMain();

    const itemDel = (item) => {
        if (addArray.length <= 1) {
            ElMessage({
                message: '至少包含一个子图文',
                type: 'warning',
            })
            return;
        }

        ElMessageBox.confirm(
            '确认要删除该子图文?',
            '温馨提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'Warning',
            }
        )
            .then(() => {
                const findIndex = addArray.findIndex(function (i) {
                    return i.id === item.id;
                })
                addArray.splice(findIndex, 1);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }).catch(()=>{});
    }

    const editChange = (editor) =>{
         if(selectIndex.value === -1){
              valueHtml.value = editor.getHtml();
         }else{
             addArray[selectIndex.value].body = editor.getHtml();
         }
    }
    const router = useRouter();
    const route = useRoute();
    onMounted(async ()=>{
      const pid = route.query.pid;
      if(!pid){
        return;
      }
      console.info("pid", pid);
      const queryParams = {
        pageNum: 1,
        pageSize: 100,
        pusername: publicAccount.selectid,
        pid: pid,
        status: 1
      };
      const result = await listImagetext(queryParams);
      if(result.code === 200){
         const rows= result.rows;
         const main=rows[0];
         dialogImageUrl.value = main.materialKey;
         tempImageUrl.value = main.materialKey;
         title.value = main.title;
         contentsummary.value = main.summary;
         valueHtml.value = decodeURIComponent(main.body);
         tempHtmlValue.value = decodeURIComponent(main.body);
         originalLink.value = main.originalUrl
         rows.forEach((item,index)=>{
              console.info("index",index)
             if(index ===0){
               addArray.splice(0,1);
               showContent.value = false;
               showContextType.value = true;
               showNetConfig.value = false;
             }
             if(index>0){
                 addArray.push({
                   body: decodeURIComponent(item.body),
                   id: item.id,
                   imgUrl: item.materialKey,
                   mainTitle: item.title,
                   originalLink: item.originalUrl,
                   showFlag: false,
                   subTitle: item.summary
                 })
             }
         })
         console.info("addArray",addArray);
      }
    });

    const save = () =>{
         const pid = (route.query.pid ===undefined? Date.now():route.query.pid);
         const data = [
             {
              pid: pid,
              pusername: username,
              materialKey: dialogImageUrl.value,
              title: title.value,
              summary: contentsummary.value,
              creationTime: parseTime(new Date()),
              suborder: 0,
              "body": encodeURIComponent(''+valueHtml.value),
              originalUrl: originalLink.value,
              shareable: 0,
              isShowCover: checked1.value ? 0 : 1,
              status: 1,
               type:1
            }
         ];

         addArray.forEach((item,index)=>{
            console.info("item",item);
             data.push({
               pid: pid,
               body: encodeURIComponent(item.body),
               creationTime: parseTime(new Date()),
               isShowCover: checked1.value ? 0 : 1,
               materialKey: item.imgUrl,
               originalUrl: item.originalLink,
               pusername: username,
               shareable: 0,
               status: 1,
               suborder: index+1,
               summary: item.subTitle,
               title: item.mainTitle,
               type: 1
             })
         })
          let error =false;
          addArray.forEach((item,index)=>{
                if(item.body ===''){
                   ElMessage.error('body为空');
                  error =true;
                }
          });
         console.info("Save now data",data);
         if(!error) {
           batchAddImagetext(data).then(resp => {
             console.info("resp ", resp);
           })
         }
        router.push('/publicAccountManager/index?name=' + name + '&username=' + username);
    }

</script>

<style scoped lang="scss">

    .bgc{
        background-color: rgba(0, 0, 0, 0.4);
        z-index: 10;
    }

    .secondary-material-title{
        padding: 10px;
        padding-right: 0;
        display: inline-block;
        width: 250px;
        word-break: break-all;
    }

    .add-sub-img-text{
        cursor: pointer;
        text-align: center;
        font-size: 40px;
        height: 25px;
        line-height: 25px;
        color: #ddd;
    }

    .material-edit-pan2{
        position: absolute;
        top: 0;
        width: 100%;
        height: 256px;
        z-index: 1;
        background-color: rgba(0,0,0,.4);

        .edit-pan-content {
            padding-top: 30px;
            display: flex;
            align-items: center;
            justify-content: space-evenly;
            .edit-pan-left{
                cursor: pointer;
                display: inline-block;
                width: 36px;
                line-height: 36px;
                height: 36px;
                background-size: 50%;
                background-repeat: no-repeat;
                background-position: 50%;
                cursor: pointer;
                background-color: #fff;
                border-radius: 18px;
                background-image: url();
            }

            .edit-pan-right{
                cursor: pointer;
                display: inline-block;
                width: 36px;
                line-height: 36px;
                height: 36px;
                background-size: 50%;
                background-repeat: no-repeat;
                background-position: 50%;
                cursor: pointer;
                background-color: #fff;
                border-radius: 18px;
                background-image: url();
            }
        }
    }

    .secondary-material{
        margin-top: 10px;
        height: 100px;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        text-align: left;
        background-image: url();
        background-repeat: no-repeat;
        background-position: 50%;



        img {
            position: absolute;
            right: 0;
            padding: 10px;
        }

        .is-hover-shadow:hover{
            box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        }
    }


    .content-type{
        position: relative;
        text-align: left;

        .quill-editor{
            margin-top: 20px;
        }
        .content-type-edit-check{
            text-align: right;
            position: relative;
            right: 20px;
            top: 10px;
            font-size: 14px;
            color: #4e7cfd;
        }

        .edit-content-original-link{
            text-align: left;
            font-size: 14px;
            color: #4e7cfd;
            line-height: 40px;
        }

        .content-select{
            text-align: right;
            position: relative;
            right: 40px;
            top: 10px;
            font-size: 14px;
            color: #4e7cfd;
        }
        .content-type-edit-check{
            text-align: right;
            position: relative;
            right: 20px;
            top: 10px;
            font-size: 14px;
            color: #4e7cfd;
        }
    }

    .view-content-type {
        padding-bottom: 20px;
        border: 1px solid #ddd;
        border-radius: 4px;

        .flex-row{
            display: flex;
            -webkit-box-direction: normal;

            .cursor-point{
                cursor: pointer;
            }
            .flex-column{
                 display: flex;
                flex-direction: column;
            }
            .eidt-text{
                margin: 10px 40px;
                text-align: center;
            }

            .m-t-10 {
                margin-top: 10px;
            }

            .goto-net{
                margin: 10px 40px;
                text-align: center;
            }
        }
        .view-content-type-title {
            padding-left: 20px;
            padding-top: 10px;
            text-align: left;
            font-size: 14px;
            color: #333;
            line-height: 40px;
        }
    }

    .m-t-20 {
        margin-top: 20px;
    }

    .box-card {
        width: 100%;
        height: 40px;
    }

    .edit-tips {
        font-size: 20px;
        text-align: left;
    }

    .edit-content-summary, .edit-content-majorpic, .edit-content-title {
        text-align: left;
        font-size: 14px;
        color: #333;
        line-height: 40px;
    }

    :deep(.hide .el-upload--picture-card) {
        display: none;
    }

    .main-material {
        min-height: 250px;
        background-image: url();
        background-repeat: no-repeat;
        background-position: 50%;

        .main-material-title {
            position: absolute;
            top: 230px;
            color: white;
            background-color: gray;
            width: 310px;
            white-space: nowrap;
        }
  .material-edit-pan{
    display: flex;
    align-items: center;
    align-content: center;
    position: absolute;
    margin-top: 16px;
    cursor: pointer;
    top: 0;
    width: 312px;
    height: 312px;

    /*z-index: 1;*/
    /*background-color: rgba(0,0,0,.4);*/

    .edit-pan-left{
      margin: auto;
      display: inline-block;
      width: 36px;
      line-height: 36px;
      height: 36px;
      background-color: #fff;
      border-radius: 18px;
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: 50%;
      background-image: url();
    }
  }
}



</style>
